//
//  FinancaialBalanceAllViewController.m
//  rrbi
//
//  Created by MyMac on 2019/5/6.
//

#import "FinancaialBalanceAllViewController.h"
#import "FinancaialBalanceStateCell.h"
#import "FinancaialOrderModel.h"
#import "UICustomDatePicker.h"

@interface FinancaialBalanceAllViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) UITableView *tabelView;
@property (nonatomic, strong) NSMutableArray *mainArray;

@property (nonatomic, assign) NSInteger page;
@property (nonatomic, strong) UIButton *todayButton;
@property (nonatomic, strong) UIButton *weekButton;
@property (nonatomic, strong) UIButton *monthButton;
@property (nonatomic, strong) UIView *lineView;

@property (nonatomic, copy) NSString *timeType;


@end

@implementation FinancaialBalanceAllViewController
- (NSMutableArray *)mainArray {
    if (!_mainArray) {
        _mainArray  = [NSMutableArray array];
    }
    return _mainArray;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.timeType = @"2";
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"余额流水记录";
    [self createTAbelView];
    
    [self getData];
    
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"日期(1)"] style:UIBarButtonItemStylePlain target:self action:@selector(searchButtonClick)];
}
- (void)createTAbelView {
    self.tabelView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-SafeAreaTopHeight) style:UITableViewStyleGrouped];
    self.tabelView.delegate = self;
    self.tabelView.dataSource = self;
    [self.view addSubview:self.tabelView];
    self.tabelView.showsVerticalScrollIndicator = NO;
    self.tabelView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tabelView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    
    if (@available(iOS 11.0, *))
    {
        self.tabelView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        self.tabelView.estimatedRowHeight = 0;
        self.tabelView.estimatedSectionFooterHeight = 0;
        self.tabelView.estimatedSectionHeaderHeight = 0;
    }
    
    [self.tabelView registerNib:[UINib nibWithNibName:NSStringFromClass([FinancaialBalanceStateCell class]) bundle:nil] forCellReuseIdentifier:@"financaialBalanceStateCell"];
    //self.tabelView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(getMoreData)];
    [self createHeadTabelView];
}

- (void)createHeadTabelView {
    
    UIView *headView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 50)];
    headView.backgroundColor = [UIColor colorWithRed:242.0/255.0 green:243.0/255.0 blue:244/255.0 alpha:1];

    
    self.todayButton = [[UIButton alloc]initWithFrame:CGRectMake(30, 0, 50, 48)];
    [self.todayButton setTitle:@"今天" forState:UIControlStateNormal];
    [self.todayButton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    self.todayButton.titleLabel.font= [UIFont systemFontOfSize:16];
    self.todayButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [self.todayButton addTarget:self action:@selector(todayButtonAction) forControlEvents:UIControlEventTouchUpInside];
    [headView addSubview:self.todayButton];
    
    self.weekButton = [[UIButton alloc]initWithFrame:CGRectMake(SCREEN_WIDTH*0.5-50, 0, 100, 48)];
    [self.weekButton setTitle:@"最近7日" forState:UIControlStateNormal];
    [self.weekButton setTitleColor:[UIColor colorWithRed:0.0/255.0 green:199.0/255.0 blue:0.0/255.0 alpha:1] forState:UIControlStateNormal];
    self.weekButton.titleLabel.font= [UIFont systemFontOfSize:16];
    [self.weekButton addTarget:self action:@selector(weekButtonAction) forControlEvents:UIControlEventTouchUpInside];
    [headView addSubview:self.weekButton];
    self.monthButton = [[UIButton alloc]initWithFrame:CGRectMake(SCREEN_WIDTH-20-100, 0, 100, 48)];
    [self.monthButton setTitle:@"最近一月" forState:UIControlStateNormal];
    [self.monthButton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    self.monthButton.titleLabel.font= [UIFont systemFontOfSize:16];
    self.monthButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    [self.monthButton addTarget:self action:@selector(monthButtonAction) forControlEvents:UIControlEventTouchUpInside];
    [headView addSubview:self.monthButton];
    
    
    self.lineView = [[UIView alloc]initWithFrame:CGRectMake(SCREEN_WIDTH*0.5-100*0.5, 48, 100, 1.5)];
    self.lineView.backgroundColor = [UIColor colorWithRed:0.0/255.0 green:199.0/255.0 blue:0.0/255.0 alpha:1];
    [headView addSubview:self.lineView];
    
    self.tabelView.tableHeaderView = headView;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.mainArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 35;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return nil;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return nil;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.00001;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.00001;;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    FinancaialBalanceStateCell *cell = [tableView dequeueReusableCellWithIdentifier:@"financaialBalanceStateCell"];
    
    FinancaialOrderModel *model = self.mainArray[indexPath.row];
    [cell updataDataWithModel:model];
    
    return cell;
}

#pragma mark - 数据请求
-(void)getData{
    
    [self getDataWithPageNum:1 isHeader:YES];
    
}

-(void)getMoreData{
    
    [self getDataWithPageNum:self.page isHeader:NO];
    
}

- (void)getDataWithPageNum:(NSInteger)pageNum isHeader:(BOOL)isHeader{
    
//    //    index_get_order","pay_status":"0","uid":"405","page":"1","token":"888061","pagesize":"10"
//    NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
//    [dic setValue:[DBInfoDefault userInfo].user_uid forKey:@"uid"];
//    [dic setValue:[DBInfoDefault userInfo].user_token forKey:@"token"];
//    [dic setValue:@(pageNum) forKey:@"page"];
//    [dic setValue:@"10" forKey:@"pagesize"];
//    [dic setValue:self.searchTextFiled.text forKey:@"likekey"];
    
    
    AFHTTPSessionManager *mgr=[AFHTTPSessionManager manager];
    NSDictionary* arg = @{
                          @"ru_id":[UserModel sharedInstanced].ru_Id,
                          @"ince":@"liushui_all_list",
                          @"type":self.timeType
                          };
    
    NSString *URL = [NSString stringWithFormat:@"%@%@",BaseUrl,@"liushui_all_list"];
    [mgr POST:URL parameters:arg progress:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        [WMHelper outPutJsonString:responseObject];
        
        NSInteger flag = [[responseObject objectForKey:@"ret"]integerValue];
        if(flag == 200){
            
            NSMutableArray *tempArr = [NSMutableArray array];
            tempArr = [FinancaialOrderModel mj_objectArrayWithKeyValuesArray:[responseObject objectForKey:@"liushui"]];
            
            if (isHeader) {
                self.page = 1;
                self.tabelView.mj_footer.state = MJRefreshStateIdle;
                [self.mainArray removeAllObjects];
                [self.mainArray addObjectsFromArray:tempArr];
                
                self.page++;
            }else {
                [self.tabelView.mj_footer endRefreshing];
                if (tempArr.count > 0) {
                    [self.mainArray addObjectsFromArray:tempArr];
                    self.page++;
                }else{
                    [self.tabelView.mj_footer endRefreshingWithNoMoreData];
                    
                }
            }
            
            [self.tabelView reloadData];
            
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error)  {
        if (isHeader) {
            [self.tabelView.mj_header endRefreshing];
            self.page = 1;
        }else {
            [self.tabelView.mj_footer endRefreshing];
            self.page--;
        }
        [self hidHUD:@"网络异常"];
    }];
    
}

- (void)todayButtonAction {
    [self.todayButton setTitleColor:[UIColor colorWithRed:0.0/255.0 green:199.0/255.0 blue:0.0/255.0 alpha:1] forState:UIControlStateNormal];
    [self.weekButton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    [self.monthButton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    self.lineView.frame = CGRectMake(20, 48, 50, 1.5);
    
    self.timeType = @"1";
    [self getData];
}

- (void)weekButtonAction {
    [self.todayButton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    [self.weekButton setTitleColor:[UIColor colorWithRed:0.0/255.0 green:199.0/255.0 blue:0.0/255.0 alpha:1] forState:UIControlStateNormal];
    [self.monthButton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    self.lineView.frame = CGRectMake(SCREEN_WIDTH*0.5-100*0.5, 48, 100, 1.5);
    
    self.timeType = @"2";
    
    [self getData];
}
- (void)monthButtonAction {
    [self.todayButton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    [self.weekButton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    [self.monthButton setTitleColor:[UIColor colorWithRed:0.0/255.0 green:199.0/255.0 blue:0.0/255.0 alpha:1] forState:UIControlStateNormal];
    self.lineView.frame = CGRectMake(SCREEN_WIDTH-15-80, 48, 80, 1.5);
    
    self.timeType = @"3";
    
    [self getData];
}

- (void)searchButtonClick {
    
    __weak typeof(self) weakSelf = self;
    [UICustomDatePicker showCustomDatePickerAtView:self.view choosedDateBlock:^(NSDate *date) {
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyy-MM-dd"];
        NSString *strDate = [dateFormatter stringFromDate:date];
        
        weakSelf.timeType = strDate;
        
        UIView *tableHeaderView = weakSelf.tabelView.tableHeaderView;
        tableHeaderView.frame = CGRectMake(0, 0, SCREEN_WIDTH, 0.000001);
        [weakSelf.tabelView setTableHeaderView:tableHeaderView];
        [weakSelf.tabelView.tableHeaderView setHidden:YES];
        [weakSelf getData];
    } cancelBlock:^{
        
    }];
    
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
